package com.cn.fw4j.mvc.servlet.impl;

import groovy.lang.GroovyObject;

import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cn.fw4j.container.impl.GroovyController;
import com.cn.fw4j.container.inter.IController;
import com.cn.fw4j.ioc.annotation.Fw4jSpringIoc;
import com.cn.fw4j.ioc.impl.Fw4jSpringPlugs;
import com.cn.fw4j.ioc.inter.IFw4jSpringPlugs;
import com.cn.fw4j.mvc.servlet.inter.IServletController;
import com.cn.fw4j.util.ClassHelper;
import com.cn.fw4j.util.groovy.GroovyLoaderHelper;
import com.cn.fw4j.util.request.parameter.OutParam;

/**
 * 
 * @author 穆仁超
 *
 */
public class GroovyServletController extends ServletController implements IServletController{
	
	private final static Logger logger = LoggerFactory.getLogger(GroovyServletController.class);
	private final static GroovyLoaderHelper groovy = GroovyLoaderHelper.getInstance();
	private final static IController ic = GroovyController.getInstance();

	@Override
	public void controller(HttpServletRequest request,
			HttpServletResponse response, String urlPath) {
		 
    	 try {
    		String call = getValue(urlPath);
    		if(call == null)return;
    		OutParam out = newOutParam(request);
			out.put("basePath", basePath(request));
    		String[] c  = call.split("[$]");
			Class<?> cl = groovy.getGroovyClass(c[0]);
			logger.debug("create class "+cl.getSimpleName());
			String template = getTemplate(cl);
			Method m = ClassHelper.getMethodByName(cl.getMethods(), c[1]);
			if(m != null){
				List<Object> args = parameters(request, response, m,out);
				GroovyObject go = groovy.getGroovyInstance(c[0]);
				this.setProperty(cl.getMethods(), go);
				this.decorator(m, args);
				Object obj = go.invokeMethod(c[1], args);
				if(c.length>2)
					printJson(response, c[2], obj);
				pageTemplate(request, response, template, out, obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据注解设置字段的值
	 * @param fields
	 * @param instance
	 */
	private void setProperty(Method[] fields,GroovyObject go){
			for(Method field : fields){
				Fw4jSpringIoc ioc =	field.getAnnotation(Fw4jSpringIoc.class);
				if(ioc != null){
					IFw4jSpringPlugs ifsp = new Fw4jSpringPlugs();
					Object obj = ifsp.getBean(ioc.value());
					go.invokeMethod(field.getName(),obj);
				}
			}
	}
	
	/**
	 * 获取url对应的类
	 * @param urlPath
	 * @return
	 */
	private String getValue(String urlPath){
		   if(ic != null){
				if(urlPath.startsWith("GET")){
					return ic.gets(urlPath);
				}else if(urlPath.startsWith("POST")){
					return ic.posts(urlPath);
				}else if(urlPath.startsWith("PUT")){
					return ic.puts(urlPath);
				}else if(urlPath.startsWith("DELETE")){
					return ic.deletes(urlPath);
				}
		   }
		   return null;
	}
}
